﻿namespace ChessToys.ChessController
{
    using System;
    using System.Collections.Generic;
    using ChessToys;

    public class PawnUnitBoardHeuristic : IBoardHeuristic
    {
        private static IDictionary<Type, int> PAWN_UNITS = new Dictionary<Type, int>();

        static PawnUnitBoardHeuristic()
        {
            PAWN_UNITS.Add(typeof(Pawn), 100);
            PAWN_UNITS.Add(typeof(Knight), 275);
            PAWN_UNITS.Add(typeof(Bishop), 325);
            PAWN_UNITS.Add(typeof(Rock), 465);
            PAWN_UNITS.Add(typeof(Queen), 900);
        }

        /// <inheritdoc />
        public double Heuristic(Board board)
        {
            // pawn units for white
            int whitePawnUnits = GetPawnUnits(board, Color.White);
            // black advantage
            if (whitePawnUnits == 0)
            {
                return 1;
            }
            // pawn units for black
            int blackPawnUnits = GetPawnUnits(board, Color.Black);
            // white advantage
            if (blackPawnUnits == 0)
            {
                return 0;
            }
            // compute heuristic
            return ((double)blackPawnUnits) / ((double)whitePawnUnits);
        }

        private int GetPawnUnits(Board board, Color color)
        {
            // start to count
            int pawnUnits = 0;
            foreach (Position position in board)
            {
                IPiece piece = board[position];
                if (piece != null && piece.Color == color)
                {
                    pawnUnits += PAWN_UNITS[piece.GetType()];
                }
            }
            // return result
            return pawnUnits;
        }
    }
}
